package com.rslai.base.tool.servertest.command;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.rslai.base.tool.servertest.context.Context;
import com.rslai.base.tool.servertest.response.Response;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;

public class ExamplesCommand extends StepCommand {
    private List<Map<String, String>> examples;
    private static final Splitter SPLITTER = Splitter.on("@@$$@@").trimResults();

    public ExamplesCommand(String body) throws IOException {
        BufferedReader reader = new BufferedReader(new StringReader(body));
        try {
            String line = null;
            List keys = readKeys(reader);
            this.examples = new ArrayList();
            while ((line = reader.readLine()) != null)
                this.examples.add(readExample(keys, line));
        } finally {
            IOUtils.closeQuietly(reader);
        }
    }

    private Map<String, String> readExample(List<String> keys, String line) {
        Iterable result = SPLITTER.split(line);
        List values = covertToList(result);
        if (values.size() != keys.size())
            throw new RuntimeException(String.format("数据驱动的Case数据格式错误:表头有%s字段，而值有%s字段", new Object[]{Integer.valueOf(keys.size()), Integer.valueOf(values.size())}));
        Map examples = new HashMap();
        for (int i = 0; i < keys.size(); i++) {
            examples.put(keys.get(i), values.get(i));
        }
        return examples;
    }

    private List<String> covertToList(Iterable<String> values) {
        Iterator iterator = values.iterator();
        ArrayList result = new ArrayList();
        while (iterator.hasNext()) {
            String value = (String) iterator.next();
            result.add(value);
        }
        if (Strings.isNullOrEmpty((String) result.get(0))) {
            result.remove(0);
        }
        if (Strings.isNullOrEmpty((String) result.get(result.size() - 1))) {
            result.remove(result.size() - 1);
        }
        return result;
    }

    private List<String> readKeys(BufferedReader reader) throws IOException {
        String line = reader.readLine();
        return covertToList(SPLITTER.split(line));
    }

    public Response doExecute(Response param, Context context) throws Throwable {
        return param;
    }

    protected StepCommand doClone() {
        return new ExamplesCommand(this.examples);
    }

    public ExamplesCommand(List<Map<String, String>> examples) {
        this.examples = examples;
    }

    public Map<String, Object> toReport() {
        return new HashMap();
    }

    public List<Map<String, String>> getExamples() {
        return this.examples;
    }
}
